using Microsoft.AspNetCore.Mvc;
using mvc.Models;
using mvc.Db;
using System;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using mvc.IR;
using System.Collections.Generic;
namespace mvc.Controllers
{
    public class ShopController:Controller
    {
        
        public ERe<Product> _Rproduct = new ERe<Product>();

        public ERe<Category> _Rcategory = new ERe<Category>();
        public IList<Product> product;

        public IActionResult Index()
        {
            if(_Rcategory.table.FirstOrDefault()==null)
            {
                _Rcategory.Insert(new Category{
                     CategoryName="手机类"
                });
            }
            
            product=_Rproduct.table.Where(x=>x.IsDeleted==false).ToList();

            return View(product);
        }


        public IActionResult AddorEndit(int id){
            if(id==0){
                return View();
            }
            var product = _Rproduct.table.Where(x=>x.Id==id).FirstOrDefault();
            return View(product);
        }

        public IActionResult Save(productObj obj){
            if(obj.Id==0){
                _Rproduct.Insert(new Product{
                    ProductName=obj.ProductName,
                    Supplier= obj.Supplier,
                    Price = obj.Price,
                    Stock = obj.Stock,
                    Remarks = obj.Remarks
                });
            }else{
                var product=_Rproduct.table.Where(x=>x.Id==obj.Id).FirstOrDefault();
                product.ProductName = obj.ProductName;
                product.Supplier=obj.Supplier;
                product.Price =obj.Price;
                product.Stock= obj.Stock;
                product.Remarks = obj.Remarks;
                _Rproduct.Update(product);
            }
            return Ok();
        }


        public IActionResult Delete(int id){
            _Rproduct.Delete(id);
            return RedirectToAction("Index");
        }

        public IActionResult Select(SelectObj obj){
            if(obj.Select=="1"){
                product = _Rproduct.table.Where(x=>x.ProductName.Contains(obj.Str)).ToList();
            }else if(obj.Select=="2"){
                product = _Rproduct.table.Where(x=>x.Id==int.Parse(obj.Str)).ToList();
            }else{
                product = _Rproduct.table.Where(x=>x.Id==int.Parse(obj.Str)).ToList();
            }
            return Json(product);
        }

    }
}